<?php 
include_once( 'config.php' );
$DT_QST = $_SERVER['QUERY_STRING'];//当前url路径
parse_str($DT_QST, $arr);
if(!isset($arr['Action']) || empty($arr['Action']))
{
	echo 'action:参数为空。请检查！';
}
$action = $arr['Action'];
if ($action != "AutoBind" && $action != "UnautoBind" && $action != "LoginInSession")
{
	//调用WebService解密方法
	$action = soap_client('Decrypt',$arr['Action']);
}
//echo $action;exit;
switch ($action)
{
	//登录信息处理
	case "LoginIn":
		LoginIn();
		break;
	//获取Session
	case "LoginInSession":
		LoginInSession();
		break;
	//自动生成(自动创建平台账号)
	case "AutoBind":
		AutoBind();
		break;      
	//绑定指定平台账号
	case "UnautoBind":
		UnautoBind();
		break;
	//绑定
	case "UserBind":
		UserBind();
		break;
	case "LoginOut":
		LoginOut();
	break;
	case "PLoginIn":
		PLoginIn();
	break;
	
	default:
		echo 'ko';
		break;

}
	//
	function LoginInSession()
	{
				//利用Guid生成随机码http://**/member/wtotd.php?action=LoginInSession
			//$str = "F38DB71A691F0462A4B1EDA234AB54D1";
			$ran = rand(10000,99999);
			//将随机码存储在Session中
			$_SESSION["randpwd"] = $ran;
			//string aa = HttpContext.Current.Request.Url.ToString().Split('?')[0];
			//显示的为网页
			//Response.ContentType = "text/plain";
			//将随机码的值传到Js文件中
			echo $ran.'|'.WTOTD_SECRET;
	}
    //登录信息处理
    function LoginIn()
    {
        //用get方式获取result(父类判断)
        global $arr;
        //判断result是否唯为空
		$result = soap_client('Decrypt',$arr['Result']);
		$user = $arr['User']; // 未解密
		$ReturnUrl = $arr['ReturnUrl']; //返回url
		$user1 = soap_client('Decrypt',$arr['User']);
        if ($result == NULL || $result == "")
        {
            //Response.Redirect("ppp.aspx");
        }
        //调用WebService解密方法解密以下参数:1、result2、type
      
        //result = Encryption.Encryption.Decrypt(result);

        //当result解密后为-1时  用户名密码错误
        if ($result == "1")
        {
			//exit;
            echo "<script>alert('用户名密码错误！');location.href='{$ReturnUrl}?a=1&isuserandpwderr=aaa'</script>";
        }
        //当result解密后为2时   未绑定用户
        else if ($result == "2")
        {
            //提示"平台用户未绑定"并跳转到绑定方式选择页面
			 echo "<script>alert('平台用户未绑定！');location.href='{$ReturnUrl}?user={$user}&isuserandpwderr=ccc&RandPwd={$arr['RandPwd']}';</script>";
        }
        //当result解密后为3时   登录成功
        else if ($result == "3")
        {
             //执行自动登录(1、随机码)
			//http://www.jgj.cc/member/wtotd.php?Result=DB93DEA7FEC65D71&User=B1EF553A4C521351&RandP=969FBEAC4FC5DB40&ReturnUrl=http://www.jgj.cc/member/login.php?user=4237E4CF2A16AB841375832258503053?user=4237E4CF2A16AB841375832258503053&Action=AFB584190BFF7EB4
            if (autoLogin($arr["RandP"],$user1))
            {
                //提示"成功"并跳转到平台页面
				
                echo "<script>alert('成功！');location.href='{$ReturnUrl}'</script>";
            }
            else
            {
                //提示"登陆失败"并跳转到登录页面
				//echo 'ko';exit;
                echo "<script>alert('登陆失败！平台账号:".$user1."不存在');location.href='{$ReturnUrl}?isuserandpwderr=aaa'</script>";
            }
        }
        else 
        {
             echo "<script>alert('错误，请重新登录！');location.href='{$ReturnUrl}&isuserandpwderr=aaa'</script>";
        }
    }
	
	    //绑定指定平台账号http://www.jgj.cc/member/wtotd.php?user=destoon&pwd=mar_8088&Action=UnautoBind
    function UnautoBind()
    {
        //获取用户名和密码
        $LoginName = $_REQUEST["user"];
        $PassWord = $_REQUEST["pwd"];
        $msg = '';
        // bool flag = validater(LoginName, PassWord);
        //平台验证功能(验证用户名密码是否正确，true表示正确，false表示错误)
        $flag = validater($LoginName, $PassWord);
        if ($flag == true)
        {
            //将返回信息用'|'拼接(1、随机码2、当前处理文件的地址)注意先后顺序
            $msg = WTOTD_SECRET;
        }
        else
        {
            $msg = "";
        }
       echo $msg;
    }
    /// <summary>
    /// 验证用户名密码是否存在
    /// </summary>
    /// <param name="user"></param>
    /// <param name="pwd"></param>
    /// <returns>存在 ture 不存在false</returns>
    function validater($user, $pwd)
    {
			global $db;
			$pwd = md5(md5($pwd));
			$user = $db->get_one("SELECT * FROM member WHERE `username`='{$user}' and `password`='{$pwd}' limit 0,1");
			if($user) 
			{
				return true;
			} 
			else 
			{
				return false;
			}
    }
	 /// <summary>
    /// 绑定
    /// </summary>
    function UserBind()
    {
	
        //用get方式获取result(父类判断)
        global $arr,$db;
        //判断result是否唯为空
		$result = soap_client('Decrypt',$arr['Result']);
		$user = $arr['User']; // 未解密
		$user1 = soap_client('Decrypt',$arr['User']);
		$ReturnUrl = $arr['ReturnUrl']; //返回url
		$RandP = $arr['RandP'];//没加密
        //判断result参数是否为空
       
        //调用WebService解密方法解密以下参数:1、result
	// echo autoLogin($arr["RandP"],$user1,1);exit;
        //当result解密后为1时            
        if ($result == "1")
        {
            //提示"已经绑定"并跳转到平台页面
            echo "<script>alert('该帐号已经绑定过帐号！');location.href='{$ReturnUrl}'</script>";
        }
        //当result解密后为2时  
        else if ($result == "2")
        {
                //提示"用户名已经被使用"并返回到绑定方式选择界面
            echo "<script>alert('用户名已经被使用！');location.href='{$ReturnUrl}&isuserandpwderr=ccc'</script>";exit;
        }
        //当result解密后为3时
        else if ($result == "3")
        {
		
            //执行自动登录
            if (autoLogin($arr["RandP"],$user1,1))
            {
				
				$db->query("update member set RandP = '".$RandP."' where username='{$user1}'");
                //提示"并返回到绑定方式选择界面"并返回到平台界面
                echo "<script>alert('绑定并登陆成功！');location.href='{$ReturnUrl}'</script>";
            }
            else
            {
                //提示"登陆失败"并返回到登陆界面
				//echo 'ko';exit;
                echo "<script>alert('登陆失败！！平台平台账号".$user1."未注册');location.href='{$ReturnUrl}&isuserandpwderr=aaa'</script>";
            }
        }
    }
	
	/// <summary>
    /// 自动登录 
    /// </summary>
    /// <param name="context"></param>
    /// <param name="randpwd"></param>
    /// <returns>成功：true,失败：false</returns>
    function autoLogin($randpwd,$user1,$true=0)
    {
		global $db;
		$rand = '';
		if($true)
		{
			$rand = $randpwd;//如果是未绑定用户 默认没验证码
			
		}
		else
		{
       	 	$rand = get_randp($user1);//如果是绑定用户 获取本平台随机验证码
      		if ($rand == NULL)
			{
            	return false;
			}
		}
      	$User = soap_client('Decrypt',$_REQUEST['User']);//解密
        if ($randpwd == $rand)
        {
            //成功 执行平台登录
			$user = $db->get_one("select * from member where username='{$User}' limit 1");
			//print_r($user);
			if($user)
			{
				$_SESSION["username"] = $user['username'];
				return true;
			} 
			else 
			{
				 return false;
			}
            
        }

    }
	    /// <summary>
    /// 绑定插入数据库(自动注册)
    /// </summary>
    /// <param name="context"></param>
    /// <param name="randpwd"></param>
    /// <returns>成功：true,失败：false</returns>
    function autoRegister($user, $pwd , $randpwd=0)
    {
        //调用WebService解密方法解密以下参数:1、randpwd
        //获取存在Session中的randpwd
        //$rand = $_SESSION["randpwd"];
        //Session中的randpwd和传过来的rand一致，则插入数据库
		$randpwd = soap_client('Decrypt',$randpwd);//解密
		$member['username']=$user;
		$member['password']=md5(md5($pwd));
		$member['RandP']=$randpwd;
        if ($randpwd==$_SESSION["randpwd"])
        {
            //插入数据库            
            autoreg($member);
			return true;
        }
		else
		{
       	   return false;
		}
    }
	 //自动生成(自动创建平台账号)
	 //http://www.jgj.cc/member/wtotd.php?user=E428174F46267ACCB5A937343EB0A7FD&pwd=123456&Action=AutoBind
	 //http://www.wtotd.com/Interface/BindUser.aspx?zxxyyhmu=nb27025011&zxxyyhmrp=97780&zxxyyhmrurl=http://www.jgj.cc/member/login.php?user=E428174F46267ACCB5A937343EB0A7FD&isuserandpwderr=ccc&zxxyyhmauthorization=F38DB71A691F0462A4B1EDA234AB54D1
    function AutoBind()
    {
	
		//exit;
        //获取用户名、密码
        $LoginName = $_REQUEST["user"];
        $PassWord = $_REQUEST["pwd"];
       $ran = $_REQUEST["RandPwd"];
		$LoginName2 = soap_client('Decrypt',$LoginName);//解密
		if(!$LoginName2) {echo '防止手动输入参数';exit;} //防止手动输入参数
        //返回信息
        $msg = $str = '';
        $flag = userinfo($LoginName2);
		$str = $flag ? "tdb_".$LoginName2 : $LoginName2;
		$str2 = soap_client('Encrypt',$str);//加密
		//将返回信息用'|'拼接返回（1、用户名2、授权码）注意先后顺序
		//这里无论平台平台有没此账号都要自动注册
		$true = autoRegister($str, $PassWord , $ran);//自动创建
		if($true)
		{
			$msg = $str2."|".WTOTD_SECRET;
			echo $msg;exit;
		}
		else
		{
			echo 'falied';
		}
    }
	//退出
	function LoginOut()
	{
		global $arr;
        //判断result是否唯为空
		$forward = $arr['ReturnUrl'];
		$result = soap_client('Decrypt',$arr['Result']);
		if($result==1)
		{
			session_destroy();
			echo "<script>alert('退出成功！');location.href='{$forward}';</script>";exit;
		}
	}
	//平台登录
	function PLoginIn()
	{
		global $arr,$db,$MOD;
		$user1 = soap_client('Decrypt',$arr['PUser']);
		$forward = $arr['ReruenUrl'];
		$randp = get_randp($user1);
		if($randp == $arr['RandP'])
		{
			//通兑宝登录成功
			$_SESSION["username"] = $user1;
			dheader($forward);
		}
		else
		{
			
			session_destroy();
			echo ('登录失败');
		}
	}
?>